package com.javaweb.dao.impl;

import com.javaweb.dao.TagDao;
import com.javaweb.model.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository // 标记此类为数据访问对象
public class TagDaoImpl implements TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public int insert(Tag tag) {
        String sql = "insert into tb_tag (name,create_time,update_time) values (?,?,?)";
        Object[] args = new Object[]{
                tag.getName(),
                new Date(),
                new Date()
        };
        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int insertArticleTag(Integer articleId, Integer[] tags) {
        return 0;
    }

    @Override
    public List<Tag> list() {
        String sql = "select * from tb_tag";
        return jdbcTemplate.query(sql,rs->{
            List<Tag> list = new ArrayList<>();
            while (rs.next()){
                Tag Tag = new Tag();
                Tag.setId(rs.getInt("id"));
                Tag.setName(rs.getString("name"));
                Tag.setCreateTime(rs.getDate("create_time"));
                Tag.setUpdateTime(rs.getDate("update_time"));
                list.add(Tag);
            }
            return list;
        });
    }

    @Override
    public int delete(Integer tagId) {
        String sql = "delete from tb_tag where id = ?" ;

        return jdbcTemplate.update(sql,new Object[]{tagId});
    }
}
